package controllers.login;

import hprose.HproseClinetService;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import play.Logger;
import play.Play;
import play.cache.Cache;
import play.libs.Encrypt;
import utils.convert.Convert;
import utils.logs.LogsUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ning.http.util.Base64;

import component.UserBis;
import constants.APIConstants;
import constants.Constants;
import controllers.common.filter.BaseFilter;
import controllers.home.HomeAction;

public class LoginAction  extends BaseFilter {
	public static void login() {
		/*远程修改操作员密码开始*/
		/*String reset = params.get("reset");
    	if("true1".equals(reset)){
    		TreeMap<String,Object> map = new TreeMap<String,Object>();
    		map.put("pr_id", "MS_C0000001");
    		map.put("user_id", "MS_PU0000149");//MS_O0000037-宋春秋   MS_PU0000149-李东辉
    		map.put("password", "407b6a654d08c18ac61d91acfe28a68a");
    		HproseClinetService.sendMessage(MqType.PUB_ASTS_RESET_USER_PASSWORD, map, "MS_C0000001");
    	}*/
    	/*远程修改操作员密码结束*/ 
		
		
//		String doStr = params.get("do");
//		if("do".equals(doStr)){
//			Calendar cal = Calendar.getInstance();
//			cal.setTime(new Date());
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//			for(int i=0;i<6;i++){
//				cal.add(Calendar.DATE, 1);
//				Date d = cal.getTime();
//				String da = sdf.format(d);
//				
//				ProductionPlan pp = new ProductionPlan();
//				pp.create_time = new Date();
//				pp.is_delete = Constants.NORMAL;
//				pp.plan_date = da;
//				pp.plan_name = "PSC724_"+da;
//				pp.plan_state = Constants.RUNNING;
//				pp.project_id = "MS_P0000001";
//				pp.save();
//			}
//		}
		render();
	}
	
	/**
	 * 登陆执行方法
	 * 
	 * @Title: loginDo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param:
	 * @return: void
	 * @throws
	 * @author caofan
	 * @Date 2015年11月20日 上午10:01:34
	 */
	public static void loginDo() {
		String username = params.get("userName");
		String password = params.get("password");
		JSONObject json = new JSONObject();
//		if (username.equals("hcx") && password.equals("123456")) {
//			Cache.set("type", "2", "30min");
//			Cache.set("user_no", "MS_C0000001", "30min");
//			json.put("ret", "1");
//		} else 
			
		if (username.equals("admin") && password.equals("147258369")) {
			Cache.set("type", "1", "30min");
			Cache.set("user_no", "admin", "30min");
			UserBis.setCurrUser("admin","admin","1","","1","","");
			json.put("ret", "1");
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userName", username);
			map.put("password", password);
			Object [] arguments = new Object[]{map};
			String res = HproseClinetService.synCall(APIConstants.AMI_LOGINDO, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			if("服务不可用".equals(res)){
				json.put("ret", -1);
				json.put("msg","对不起，服务暂不可用，请稍候再试");
				renderJSON(json);
			}
			json = JSONObject.parseObject(res);
			if(json.get("ret").equals("1")){
				UserBis.setCurrUser(json.get("user_no")+"",json.getString("userName"),"","",json.get("type")+"",json.getString("reday_member_id"),json.getString("login_account"));
				json.put("ret", "1");
				json.put("msg","");
				renderJSON(json);
			}else{
				json.put("ret", "-2");
				json.put("msg","用户名或密码错误");
				renderJSON(json);
			}
		}
		renderJSON(json);
	}
	public static void loginOut(){
		UserBis.loginOut();
		String url = Cache.get("callback_url",String.class);
		if(StringUtils.isBlank(url)){
			url = Play.configuration.getProperty("login_url");
		}
		redirect(url);
	}
	/**
	 * 修改密码
	 * 
	 * 2015年12月31日 下午3:33:22
	 * @auth huan208050@vip.qq.com
	 */
	public static void updatePassWord(){
		String oldPass = params.get("psd");
		String newPass = params.get("psd1");
		String rePass=params.get("psd2"); 
 		Map<String, Object> map = new HashMap<String, Object>();
		map.put("old_pass", oldPass);
		map.put("re_pass", rePass);
		map.put("new_pass", newPass);
		map.put("user_name", UserBis.currLoginAccount());
 		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.USERMI_CHANGEPASSWORD, arguments, APIConstants.AUTH_HOST, APIConstants.AUTH_PORT);
		renderJSON(res);
	}
	/**
	 * 单点登录接口
	 * 
	 * 2016年1月23日 上午9:43:12
	 * @auth huan208050@vip.qq.com
	 */
	public static void singleLanding(){
		
		/**
		 * 1.获取token，通过权限平台查询该token的信息
		 * 2.将获取到的用户，客户信息放入cache，同时拿到角色权限信息，放入cache
		 * 3.将菜单放入cache，前端通过独立请求拿到菜单列表
		 * 4.拦截器对比权限进行拦截
		 */
		String msg = "校验失败";
		String url=params.get("callback");
		Cache.set("callback_url", url,"30d");
		if(StringUtils.isBlank(url)){
			flash.put("msg", "回调地址为空");
			flash.keep();
			LoginAction.error();
		}
		StringBuffer buff = new StringBuffer();
		String token = params.get("token");
		if(StringUtils.isBlank(token)){
			Logger.info("token为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		String key = Play.configuration.getProperty("md5_key", "naE6UpZDvSZZh3XqSBU3Pr7qq1BM8M3y");
		String user_id = params.get("user_id");
		
		if(StringUtils.isBlank(user_id)){
			Logger.info("用户id为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		try {
			user_id = new String(Base64.decode(user_id),"UTF-8");
			Logger.info("user_id:"+user_id);
		} catch (Exception e) {
			Logger.info("user_id解析失败");
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		
		String ip = params.get("ip");
		
		if(StringUtils.isBlank(ip)){
			Logger.info("ip为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		try {
			ip = new String(Base64.decode(ip),"UTF-8");
			Logger.info("ip:"+ip);
		} catch (Exception e) {
			Logger.info("ip解析失败");
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		
		String customer_id = params.get("customer_id");
		
		if(StringUtils.isBlank(customer_id)){
			Logger.info("customer_id为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		try {
			customer_id = new String(Base64.decode(customer_id),"UTF-8");
			Logger.info("customer_id:"+customer_id);
		} catch (Exception e) {
			Logger.info("customer_id解析失败");
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		
		String customer_name = params.get("customer_name");
		
		if(StringUtils.isBlank(customer_name)){
			Logger.info("customer_name为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		try {
			customer_name = customer_name.trim().replace(" ", "+");
			customer_name = new String(Base64.decode(customer_name),"UTF-8");
			Logger.info("customer_name:"+customer_name);
		} catch (Exception e) {
			Logger.info("customer_name解析失败");
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		
		String plat_id = params.get("plat_id");
		
 		if(StringUtils.isBlank(plat_id)){
			Logger.info("plat_id为空");
			msg =  "校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		try {
			plat_id = new String(Base64.decode(plat_id),"UTF-8");
			Logger.info("plat_id:"+plat_id);
		} catch (Exception e) {
			Logger.info("plat_id解析失败");
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		
		String sign = params.get("sign");
		Logger.info("传送过来的签名："+sign);
		if(StringUtils.isBlank(sign)){
			Logger.info("签名为空");
			msg =  "签名出错";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		StringBuffer waitSign = new StringBuffer();
		waitSign.append(token).append(user_id).append(customer_id).append(customer_name).append(plat_id).append(ip).append(key);
		Logger.info("签名原串："+waitSign.toString());
		String currSign = Encrypt.MD5(waitSign.toString());
		if(!currSign.equals(sign)){
			Logger.info("签名校验失败");
			//补充：返回地址
			msg =  "签名校验失败";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			Logger.info("返回信息:"+buff.toString());
			redirect(buff.toString());
		}
		Logger.info("数据校验通过，准备请求权限数据");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("token", token);
		map.put("user_id", user_id);
		map.put("ip", ip);
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.AUTHMI_CHECKTOKEN, arguments, APIConstants.AUTH_HOST, APIConstants.AUTH_PORT);
		//Logger.info("C层请求API,校验token结果："+res);
		if("服务不可用".equals(res)){
			msg = "服务维护中";
			msg = Base64.encode(msg.getBytes());
			buff.append(url).append("?").append("msg=").append(msg);
			redirect(buff.toString());
		}
		JSONObject json = JSONObject.parseObject(res);
		if(json!=null){
			int ret = Convert.convertToInt(json.getString("ret"),-1);
			if(ret<0){
				//补充：返回地址
				msg = "服务维护中";
				msg = Base64.encode(msg.getBytes());
				buff.append(url).append("?").append("msg=").append(msg);
				redirect(buff.toString());
			}
			/**==============================================================
			*对接拦截器获取权限数据,注入cache，开启拦截器过滤功能
			*data中包含所有
			*/
			JSONObject  roles =JSONObject.parseObject(json.getString("data"));
			Logger.info("权限数据："+roles);
			if(!roles.getString("role_data").equals("[]")&&StringUtils.isNotBlank(roles.getString("role_data"))){
				String rolesStr = roles.getString("role_data");
				JSONArray role_data = JSONArray.parseArray(rolesStr); 
				UserBis.setCurrUser(customer_id, params.get("user_name"), user_id,plat_id,"2",params.get("reday_member_id"),params.get("login_account"));
				UserBis.setCurrRight(role_data.toJSONString());
				JSONArray urls = role_data.getJSONObject(0).getJSONArray("right_data");
				Map<String,String> urlMap = new HashMap<String,String>();
				for(int k=0;k<urls.size();k++){
					JSONObject curl = urls.getJSONObject(k);
					if(curl!=null){
					String url_key = curl.getString("url");
					if(StringUtils.isNotBlank(url_key)){
						url_key=url_key.toLowerCase();
					}
					urlMap.put(url_key, "");
					}
				}
				UserBis.setCurrRightMap(urlMap);
				LogsUtils.addLogs(Constants.LOG_TYPE_LOGIN,Convert.convertToInt(user_id,-1), 1, "登录操作执行","success", params.get("login_account"), customer_name, customer_id);
				HomeAction.home();
			}else{
				msg = "权限不足";
				msg = Base64.encode(msg.getBytes());
				buff.append(url).append("?").append("msg=").append(msg);
				redirect(buff.toString());
			}
			//存入cache
			//跳转至主页
		}
	}
	public static void getMenus(){
		String msg = "";
		if(StringUtils.isBlank(UserBis.currMenu())){
			UserBis.loginOut();
			StringBuffer sb = new StringBuffer();
			msg = "登录超时";
			String url = Play.configuration.getProperty("login_url");
			msg = Base64.encode(msg.getBytes());
			sb.append(url).append("?").append("msg=").append(msg);
			redirect(sb.toString());
		}else{
			renderJSON(UserBis.currMenu());
		}
	}
	public static void main(String[] args) {
		String token = "abcdefghijklmnopqrstuvwxyz";
		String user_id = "123";
		String customer_id ="MS_C0000001";
		String plat_id = "1";
		String ip="192.168.1.100";
		String key = "naE6UpZDvSZZh3XqSBU3Pr7qq1BM8M3y";
		String sign = "9cb0166f71a0943e204ec843b23d5892";
		sign = Encrypt.MD5(token+user_id+customer_id+plat_id+ip+key);
		System.out.println(sign);
	}
	/**
	 * 失败
	 * 
	 * 2016年1月25日 下午4:57:30
	 * @auth huan208050@vip.qq.com
	 */
	public static void error(){
		render();
	}
	
}
